package com.xiaohai.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaohai.common.R;
import com.xiaohai.projo.Course;
import com.xiaohai.projo.dto.CourseDto;
import com.xiaohai.projo.Teacher;
import com.xiaohai.service.CourseService;
import com.xiaohai.service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xiaohai
 * @since 2024-02-24
 */
@Slf4j
@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;

    @Autowired
    private TeacherService teacherService;

    @GetMapping("/list")
    public R<Page<CourseDto>> list(Integer currentPage, Integer pageSize, String courseName, String teacherName, Integer identity,String account) {
        Page<CourseDto> list = courseService.myList(currentPage, pageSize, courseName, teacherName, identity,account);
        return R.success(list, "获取数据成功");
    }

    @GetMapping
    public R<Course> detail(String id) {
        Course course = courseService.detail(id);
        if (Objects.isNull(course)) {
            return R.error("获取详情失败", 201);
        }
        return R.success(course, "获取详情成功");
    }

    @GetMapping("/teacherList")
    public R<List<Teacher>> teacherList() {
        List<Teacher> list = teacherService.list();
        if (Objects.isNull(list)) {
            return R.error("获取数据失败", 201);
        }
        return R.success(list, "获取数据成功");
    }

    @PostMapping
    public R<Objects> addAndUpdate(@RequestBody Course course) {
        log.info("course:{}", course);
        Integer id = course.getId();
        if (id != null) { // 修改
            Boolean b = courseService.myUpdate(course);
            if (b) {
                return R.success(null, "修改成功");
            }
            return R.error("修改失败", 201);
        } else {
            LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
            String name = course.getName();
            courseLambdaQueryWrapper.eq(name != null, Course::getName, name);
            long count = courseService.count(courseLambdaQueryWrapper);
            if (count > 0) {
                return R.error("该课程已添加，不能重复添加", 201);
            }
            boolean add = courseService.add(course);
            if (add) {
                return R.success(null, "新增成功");
            }
            return R.error("新增失败", 201);
        }
    }

    @DeleteMapping
    public R<Object> deleteById(Integer id) {
        log.info("id:{}", id);
        boolean b = courseService.delete(id);
        if (b) {
            return R.success(null, "删除成功");
        }

        return R.error("删除失败,该课程有学生正在学习", 201);
    }
}
